import { PlusBase } from "./PlusBase";
import { Redis as RedisClient, Redis, Cluster } from "ioredis";
import { IRedisOption } from "../entity/IConfig";
var Redis = require("ioredis");

export class PlusRedis extends PlusBase {
    static NAME: string = "redis";
    private _options: IRedisOption;
    private _redis: RedisClient | Cluster;
    constructor(options: IRedisOption) {
        super(PlusRedis.NAME);
        this._options = options;
    }

    async init() {
        if (this._options.cluster) {
            let nodes = this._options.cluster;
            delete this._options.cluster;
            this._redis = new Cluster(nodes, { redisOptions: this._options });
        } else {
            this._redis = new Redis(this._options);
        }
        this._redis.on("ready", this._onReady.bind(this));
        this._redis.on("disconnect", () => {
            this._redis.connect(() => {
                this.log.info("reconnect success");
            })
        });
        this._redis.on('reconnecting', (reply) => {
            this.log.warn('RedisReconnecting--' + reply);
        });
        this._redis.on('error', this._onError.bind(this));
    }

    private _onReady() {
        this.mCompleteHandle();
    }

    private _onError(err) {
        this.log.error('RedisErr--' + err);
        this.mOnFail(err);
    }

    get client(): Redis {
        return <any>this._redis;
    }
}